﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Pipes;

namespace NamedPipe.Client
{
    public sealed class ClientConnect
    {        
        public ClientConnect()
        {
        }

        public void ConnectPipeServer(string namespaceTag, string classTag, string methodTag, string variablesTag)
        {
            string mensagem = string.Empty;
            
            try
            {
                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "FxCopPipe", PipeDirection.Out, PipeOptions.Asynchronous))
                {
                    pipeClient.Connect();

                    using (StreamWriter sw = new StreamWriter(pipeClient))
                    {
                        sw.AutoFlush = true;

                        mensagem = string.Concat(Atributos.NAMESPACE, namespaceTag, Atributos.DIVIDE_MEMBERS,
                                                 Atributos.CLASS, classTag, Atributos.DIVIDE_MEMBERS,
                                                 Atributos.METHOD, methodTag, Atributos.DIVIDE_MEMBERS,
                                                 Atributos.VARIABLES, variablesTag);

                        sw.WriteLine(mensagem);
                    }
                }
            }
            catch
            {
                throw;
            }
        }

        //public void ConnectPipeServer(params Object[] msg)
        //{
        //    try
        //    {
        //        using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "FxCopPipe", PipeDirection.Out, PipeOptions.Asynchronous))
        //        {
        //            pipeClient.Connect();

        //            using (StreamWriter sw = new StreamWriter(pipeClient))
        //            {
        //                sw.AutoFlush = true;

        //                sw.WriteLine(this.SerializeObject(msg));
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        //Implementar
        //    }
        //}

        private String SerializeObject(Object obj)
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            
            try
            {
                binaryFormatter.Serialize(memoryStream, obj);

                return System.Convert.ToBase64String(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                memoryStream.Dispose();
            }
        }
    }
}
